﻿using Entity;
using System.Reflection;

namespace DAL
{
    /// <summary>
    /// 查询字典数据
    /// </summary>
    public class DictionaryList<TList, TKey, TValue>
    {
        public TKey Key { get; set; }
        public TValue Value { get; set; }
        public static List<DictionaryList<TList, TKey, TValue>> GetDictionaryList(IQueryable<TList> lists, string keyName, string valueName)
        {
            // 获取类型信息
            Type type = typeof(TList);
            // 获取键属性
            PropertyInfo keyProperty = type.GetProperty(keyName)
                ?? throw new MyCustomException($"Property {keyName} not found on type {type.Name}");

            // 获取值属性
            PropertyInfo valueProperty = type.GetProperty(valueName)
                ?? throw new MyCustomException($"Property {valueName} not found on type {type.Name}");
            // 验证属性类型是否匹配泛型参数
            if (keyProperty.PropertyType != typeof(TKey))
            {
                throw new MyCustomException($"Property {keyName} type doesn't match TKey type");
            }
            if (valueProperty.PropertyType != typeof(TValue))
            {
                throw new MyCustomException($"Property {valueName} type doesn't match TValue type");
            }
            // 创建结果对象
            var result = new List<DictionaryList<TList, TKey, TValue>>();
            // 遍历数据并构建字典
            foreach (var item in lists)
            {
                result.Add(new DictionaryList<TList, TKey, TValue>()
                {
                    Key = (TKey)keyProperty.GetValue(item)!,
                    Value = (TValue)valueProperty.GetValue(item)!
                });
            }
            return result;
        }
    }
}
